<?

class ManageController extends CFD_Controller_Action {

    public function init() {
        parent::init();
        $this->isAdmin(true);
    }

    public function statsAction() {
        $this->view->title = "System stats";

        $voucherTable = new Application_Model_Vouchers();
        $res = $voucherTable->getAdapter()->query("SELECT COUNT(*) as count FROM vouchers");
        $count = $res->fetchAll();
        $this->view->allVouchers = $count[0]['count'];

        $voucherTable = new Application_Model_Vouchers();
        $res = $voucherTable->getAdapter()->query("SELECT COUNT(*) as count FROM vouchers where purchase_users_id != 0");
        $count = $res->fetchAll();
        $this->view->purchased = $count[0]['count'];

        $voucherTable = new Application_Model_Vouchers();
        $res = $voucherTable->getAdapter()->query("SELECT COUNT(*) as count FROM vouchers where exp_date < '" . date("Y-m-d") . "'");
        $count = $res->fetchAll();
        $this->view->purchased = $count[0]['count'];

        $voucherTable = new Application_Model_Vouchers();
        $res = $voucherTable->getAdapter()->query("SELECT COUNT(*) as count FROM vouchers where exp_date >= '" . date("Y-m-d") . "'");
        $count = $res->fetchAll();
        $this->view->active = $count[0]['count'];

        $valTable = new Application_Model_Vouchers();
        $this->view->valuationsListFiltered = $this->view->valuationsList = $valTable->fetchAll(
                $valTable->select()
                        ->where('purchase_users_id = ?', '0')
                        ->where('exp_date >= ?', date('Y-m-d'))
        );
    }

    public function resellerstatsAction() {


        //Load user table modle class 
        $usersTable = new Application_Model_Users();
        //Fetch the resellers of the site
        $resellers = $usersTable->getResellers();
        $this->view->resellers = $resellers;
        $filter = 'all';

        $allVouchers = 0;
        $purchasedVouchers = 0;
        $expiredVouchers = 0;
        $activeVouchers = 0;
        $totalEarning = 0;
        $vouchersArray = Array();


        $resellerid = '';
        $boolVoucherView = false;
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            $resellerid = $postedData['resellerid'];

            $filter = $postedData['filter'];
            if ($resellerid == '') {
                Alert_View::addMessage(Alert_View::WARNING, "", "Please select a reseller.");
            } else {
                $boolVoucherView = true;



                //SessionId of the reseller
                $userId = $resellerid;


                if ($filter == 'all') {
                    $where = "reseller_user_id = '" . $userId . "'";
                } else if ($filter == 'purchased') {
                    $where = "purchase_users_id != 0 and reseller_user_id = '" . $userId . "'";
                } else if ($filter == 'expired') {
                    $where = "exp_date < '" . date('Y-m-d') . "' and reseller_user_id = '" . $userId . "'";
                } else if ($filter == 'active') {
                    $where = "exp_date >= '" . date('Y-m-d') . "' and reseller_user_id = '" . $userId . "' and purchase_users_id = '0' ";
                } else {
                    $where = "reseller_user_id = '" . $userId . "'";
                }



                $this->view->title = "Partner Voucher stats";

                //Load Voucher Model for statistics
                $voucherModel = new Application_Model_VoucherStats();

                //Count All Vouchers
                $allVouchers = $voucherModel->getVoucherCount("reseller_user_id = '" . $userId . "'");

                //Count All Purchased Vouchers
                $purchasedVouchers = $voucherModel->getVoucherCount("purchase_users_id != 0 and reseller_user_id = '" . $userId . "'");

                //Count All Expired Vouchers
                $expiredVouchers = $voucherModel->getVoucherCount("exp_date < '" . date('Y-m-d') . "' and reseller_user_id = '" . $userId . "'");

                //Count All Active Vouchers
                $activeVouchers = $voucherModel->getVoucherCount("exp_date >= '" . date('Y-m-d') . "' and reseller_user_id = '" . $userId . "' and purchase_users_id = '0' ");

                //Total Earning by Reseller
                $totalEarning = $voucherModel->getTotalVoucherEarning("purchase_users_id != 0 and reseller_user_id = '" . $userId . "'");

                //All Voucher Array
                $vouchersArray = $voucherModel->fetchVouchers($where);
            }
        }
        $this->view->resellerid = $resellerid;


        $this->view->boolVoucher = $boolVoucherView;

        $this->view->allVouchers = $allVouchers;
        $this->view->purchased = $purchasedVouchers;
        $this->view->expired = $expiredVouchers;
        $this->view->active = $activeVouchers;
        $this->view->totalEarning = $totalEarning;
        $this->view->vouchersArray = $vouchersArray;


        $this->view->filter = $filter;
    }

    private function extractMonthYear($str) {
        if (preg_match("/^(\d{4})(\-|\/)(\d{1,2})(\-|\/)(\d{1,2})$/", $str, $match)) {
            return date('Y-m-d', mktime(0, 0, 0, $match[3], $match[5], intval($match[1])));
        } else if (preg_match("/^(\d{1,2})(\-|\/)(\d{4})$/", $str, $match)) {
            return date('Y-m-d', mktime(0, 0, 0, $match[1], 1, intval($match[3])));
        } else if (preg_match("/^(\d{1,2})(\-|\/)(\d{2})$/", $str, $match)) {
            return date('Y-m-d', mktime(0, 0, 0, $match[1], 1, 2000 + $match[3]));
        } else if (preg_match("/^\d{5,6}$/", $str)) {
            $num = intval($str);
            $month = $num / 10000;
            $year = $num % 10000;
            return date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
        } else if (preg_match("/^\d{3,4}$/", $str)) {
            $num = intval($str);
            $month = $num / 100;
            $year = $num % 100;
            return date('Y-m-d', mktime(0, 0, 0, $month, 1, 2000 + $year));
        }
        return '';
    }

    public function addVoucherCodeAction() {

        //Load user table modle class 
        $usersTable = new Application_Model_Users();

        //Fetch the resellers of the site
        $resellers = $usersTable->getResellers();
        $this->view->resellers = $resellers;

        $this->view->title = "Add voucehrs to the datbase";
        $this->view->hideResult = true;

        if ($_POST ['vouchers']) {

            $offset = 0;

            $cols = array();
            foreach ($_POST as $k => $v)
                if (strpos($k, "col_") === 0) {
                    if ($v == '_')
                        $offset++;
                    $cols [$v] = (int) substr($k, 4) - 1 - $offset;
                }

            $voucherTable = new Application_Model_Vouchers ();

            $vList = explode("\n", $_POST ['vouchers']);

            $vouchers = array();
            foreach ($vList as $line) {
                $data = explode($_POST ['separator'], $line);

                $v = array(
                    'voucher' => trim($data [$cols ['voucher']]),
                    'cvv' => trim($data [$cols ['cvv']]),
                    'exp_date' => $this->extractMonthYear(trim($data [$cols ['exp_date']])),
                    'name' => trim($data [$cols ['name']]),
                    'city' => trim($data [$cols ['city']]),
                    'address' => trim($data [$cols ['address']]),
                    'zip' => trim($data [$cols ['zip']]),
                    'price' => trim($_POST['price']),
                    'reseller_user_id' => (trim($_POST['reseller']) != "") ? trim($_POST['reseller']) : "0",
                    'exists' => false
                );

                if ($v ['voucher']) {
                    $row = $voucherTable->fetchRow($voucherTable->select()->where('voucher = ?', $v ['voucher']));

                    if ($row)
                        $v ['exists'] = true;

                    $vouchers [] = $v;
                }
            }
            $this->view->vouchers = $vouchers;
            $this->view->hideForm = true;
            $this->view->hideResult = false;
        }

        if ($_POST ['serVouchers']) {
            $this->view->hideForm = true;
            $this->view->hideResult = true;
            $vouchers = unserialize(base64_decode($_POST ['serVouchers']));

            $voucherTable = new Application_Model_Vouchers ();
            $voucherRefModel = new Application_Model_VoucherRef();
            foreach ($vouchers as $voucher) {
                $voucherRow = $voucherTable->createRow($voucher);
                try {
                    $voucherid = $voucherRow->save();
                    //Condition to check that reseller is not blank and if it is case save it as ref with table
                    if ($_POST['resellerid'] != '') {
                        $voucherRefData = Array();
                        $voucherRefData['id'] = NULL;
                        $voucherRefData['user_id'] = $_POST['resellerid'];
                        $voucherRefData['voucher_id'] = $voucherid;
                        $voucherRefData['created_date'] = date('Y-m-d H:i:s');
                        $voucherRefModel->save($voucherRefData, 'id');
                    }
                } catch (Exception $e) {
                    
                }
            }

            Alert_View::addMessage(Alert_View::NOTICE, "", "New vouchers were successfully loaded to the database");
        }
    }

    public function usersAction() {
        $this->view->title = "Manage users";

        $usersTable = new Application_Model_Users();

        if ($_GET['ch']) {
            $usersTable = new Application_Model_Users();
            if ($usersTableRow = $usersTable->find((int) $_GET['ch'])) {
                $usersTableRow[0]->user_enabled = !($usersTableRow[0]->user_enabled);
                $usersTableRow[0]->save();
            }
        }

        $adapter = new Zend_Paginator_Adapter_DbSelect($usersTable->select()->order('id DESC'));

        $this->view->page = $this->_request->getParam('page');

        if (!$this->view->page)
            $this->view->page = 1;

        $res = $usersTable->getAdapter()->query("SELECT COUNT(*) as count FROM users");
        $count = $res->fetchAll();
        $count = $count[0]['count'];

        $adapter->setRowCount((int) $count);

        $paginator = $this->view->paginator = new Zend_Paginator($adapter);
        $paginator->setItemCountPerPage(7);
        $paginator->setCurrentPageNumber($this->_request->getParam('page'));
    }

    public function editAction() {
        $this->view->title = "Edit vouchers";
        $this->view->hideResult = true;
        $voucherTable = new Application_Model_Vouchers ();

        if ($_POST ['voucher']) {
            if ($_POST ['vid']) {
                $row = $voucherTable->fetchRow($voucherTable->select()->where('id = ?', $_POST ['vid']));
            }
            if (!($row)) {
                Alert_View::addMessage(Alert_View::WARNING, "", "Illegal Access");
                return;
            }
            if ($row->voucher != $_POST['voucher']) {
                $rowtest = $voucherTable->fetchRow($voucherTable->select()->where('voucher = ?', $_POST ['voucher']));
                if ($rowtest) {
                    Alert_View::addMessage(Alert_View::NOTICE, "", "Voucher number exist in the database");
                    return;
                }
            }
//  		$row = $voucherTable->createRow ();
            $row->voucher = $_POST ['voucher'];
            $row->exp_date = $_POST ['exp_date'];
            $row->name = $_POST ['name'];
            $row->address = $_POST ['address'];
            $row->city = $_POST ['city'];
            $row->zip = $_POST ['zip'];
            $row->cvv = $_POST ['cvv'];
            $row->price = $_POST ['price'];
            $row->save();
            Alert_View::addMessage(Alert_View::NOTICE, "", "Voucher was successfully changed");
        }

        if ($_GET ['id']) {
            $row = $voucherTable->fetchRow('id=' . $_GET ['id']);
            if ($row) {
                $this->view->editData = $row->toArray();
            }
            $this->view->vid = $_GET ['id'];
        }
    }

    public function deleteAction() {
        $id = $_GET['id'];
        if ($id == '')
            return;
        $this->isAdmin(true);

        $voucherTable = new Application_Model_Vouchers();
        $res = $voucherTable->getAdapter()->query("delete FROM vouchers where id = " . addslashes($id));
        $this->getResponse()->setRedirect('/manage/stats');
    }

}
